<?php
//
// interact with database
//
class News_model extends CI_Model {

	public $m_dbTableName	= "news";

	public $m_dbId			= "id";
	public $m_dbTopic		= "topic";
	public $m_dbBody		= "body";
	public $m_dbDate		= "date";

	public function __construct()
	{
		parent::__construct();
	}

	//Paging
	public function db_record_count()
	{
		return $this->db->count_all($this->m_dbTableName);
	}

	public function db_get_news($limit, $start)
	{
		$q = $this
			->db
			->limit($limit, $start)
			->order_by($this->m_dbDate, "desc")
			->get($this->m_dbTableName);
		return $q->result();
	}
	// end paging

	public function db_insert_news($a_topic, $a_body, $a_date)
	{
		$data = array(
					$this->m_dbTopic => $a_topic,
					$this->m_dbBody => $a_body,
					$this->m_dbDate => $a_date
	            );
		$this->db->insert($this->m_dbTableName, $data);	
		return TRUE;
	}

	public function db_update_news($a_id, $a_topic, $a_body)
	{
		$data = array(
					$this->m_dbTopic => $a_topic,
					$this->m_dbBody => $a_body
	            );
		$this->db->where($this->m_dbId, $a_id);
		$this->db->update($this->m_dbTableName, $data);
		return TRUE;
	}
	
	public function db_get_newslist()
	{
		$q = $this
				->db 
				->order_by($this->m_dbDate, "desc")
				->get($this->m_dbTableName);
		return $q->result();
	}

	public function db_get_row_from_id($a_id)
	{
		$q = $this
				->db 
				->where($this->m_dbId, $a_id)
				->limit(1)
				->get($this->m_dbTableName);
		
		if ($q->num_rows() > 0 ){
			return $q->row();
		}
		return FALSE;
	}

	public function db_add_new_news_by_id($a_topic, $a_body)
	{
		date_default_timezone_set("Asia/Bangkok");
		$date = date('Y-m-d H-i-s');
		$this->db_insert_news($a_topic, $a_body, $date);
		return TRUE;
	}

	public function db_delete_news($a_id)
	{
		$q = $this->db->where($this->m_dbId, $a_id);
		$q = $this->db->delete($this->m_dbTableName);
		return TRUE;
	}

}
?>
